package com.mida.bms.report.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.io.IOException;

@Configuration
@MapperScan(basePackages = DocDataSource.PACKAGE,sqlSessionFactoryRef="doc_SqlSessionFactory")
@DependsOn("loadFromDatabasePropertyConfig")
public class DocDataSource {

	static final String PACKAGE = "com.mida.bms.report.mapper";
	static final String MAPPER_LOCATION = "classpath*:mssql/doc/mapper/*.xml";
	
	@Value("${doc.data.url}")
	private String url;

	@Value("${doc.data.username}")
	private String user;

	@Value("${doc.data.passwd}")
	private String password;

	@Value("${doc.data.driver}")
	private String driverClass;
	
	@Value("${doc.data.dbType:mssql}")
	private String dbType;

	@Bean(name = "DocDataSource")
//	@Primary
	public DataSource docDataSource() {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setUrl(url.trim());
		dataSource.setDriverClassName(driverClass.trim());
		dataSource.setUsername(user.trim());
		dataSource.setPassword(password.trim());
		return dataSource;
	}

	/**
	 * 实例化数据源事务管理器
	 * 
	 * @return
	 */
	@Bean(value="docTxManager")
//	@Primary
	public DataSourceTransactionManager docTxManager() {
		return new DataSourceTransactionManager(docDataSource());
	}

	
	@Bean(name="doc_SqlSessionFactory")
//	@Primary
	public SqlSessionFactoryBean doc_SqlSessionFactory() throws IOException {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(docDataSource());
		org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
		configuration.setCallSettersOnNulls(true);
//		Interceptor[] interceptors= {new MybatisInterceptor()};
//		sqlSessionFactoryBean.setPlugins(interceptors);
		sqlSessionFactoryBean.setConfiguration(configuration);
		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
				.getResources("classpath*:"+dbType+"/doc/mapper/*.xml"));
		sqlSessionFactoryBean.setTypeAliasesPackage("com.mida.bms.report.entity");
		
		return sqlSessionFactoryBean;
	}
}
